#include <8052.h>
#include "Delay.h"
#include "LCD1602.h"
#include "MatrixKey.h"

unsigned char key_num;
unsigned int password, count;

void main() {
    LCD_Init();
    LCD_ShowString(1, 1, "MatrixKey:");
    while (1) {
        key_num = MatrixKey();
        if (key_num) {
            // 如果S1 ~ S10按键按下，输入密码
            if (key_num <= 10) {  // 1 ~ 10定义为密码区
                // 控制最多输入4位
                if (count < 4) {
                    // 密码左移1位
                    password *= 10;
                    password += key_num % 10;
                    count++;
                }
                LCD_ShowNum(2, 1, password, 4);  // 更新显示
            }
            // 如果S11按键按下，退格
            if (key_num == 11 && count > 0) {  // 判断无符号整型count防止溢出
                count--;
                password -= (password % 10);
                password /= 10;
                LCD_ShowNum(2, 1, password, 4);
            }
            // 如果S12按下，确认
            if (key_num == 12) {
                if (password == 2003) {
                    LCD_ShowString(1, 12, "RIGHT");
                    // 复位
                    while (MatrixKey() != 13) {}
                    LCD_ShowString(1, 12, "     ");
                    password = 0;
                    count = 0;
                    LCD_ShowNum(2, 1, password, 4);
                } else {
                    LCD_ShowString(1, 12, "WRONG");
                    Delay(1500);
                    LCD_ShowString(1, 12, "AGAIN");
                    password = 0;
                    count = 0;
                    LCD_ShowNum(2, 1, password, 4);  // 更新显示
                }
            }
        }
    }
}